import { Injectable, NestMiddleware, Logger } from '@nestjs/common';
import { Request, Response, NextFunction } from 'express';

/**
 * 请求日志中间件
 * 记录所有 HTTP 请求
 */
@Injectable()
export class LoggerMiddleware implements NestMiddleware {
  private logger = new Logger('HTTP');

  use(request: Request, response: Response, next: NextFunction): void {
    const { ip, method, originalUrl, body } = request;
    const userAgent = request.get('user-agent') || '';
    const startTime = Date.now();

    // 响应完成时记录日志
    response.on('finish', () => {
      const { statusCode } = response;
      const contentLength = response.get('content-length');
      const responseTime = Date.now() - startTime;

      const logMessage = `${method} ${originalUrl} ${statusCode} ${contentLength || 0}bytes - ${responseTime}ms - ${userAgent} ${ip}`;

      // 根据状态码选择日志级别
      if (statusCode >= 500) {
        this.logger.error(logMessage);
      } else if (statusCode >= 400) {
        this.logger.warn(logMessage);
      } else {
        this.logger.log(logMessage);
      }

      // 记录请求体（仅在开发环境）
      if (process.env.NODE_ENV === 'development' && Object.keys(body).length) {
        this.logger.debug(`Body: ${JSON.stringify(body)}`);
      }
    });

    next();
  }
}



